package com.ljw.punishment.mvelcondition;

import org.jeasy.rules.api.Condition;
import org.jeasy.rules.api.Facts;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import org.mvel2.integration.impl.DefaultLocalVariableResolverFactory;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lijunwei
 * @date 2025/5/21
 */
public class CustomMvelCondition implements Condition, Serializable {


    private static final long serialVersionUID = -9046997082361947582L;

    private final Serializable compiledExpression;

    private final Map<String, Object> extendParams;

    public CustomMvelCondition(String expression) {
        compiledExpression = MVEL.compileExpression(expression);
        this.extendParams = new HashMap<>();
    }

    public CustomMvelCondition(String expression, ParserContext parserContext) {
        compiledExpression = MVEL.compileExpression(expression, parserContext);
        this.extendParams = new HashMap<>();
    }

    public CustomMvelCondition(String expression, ParserContext parserContext, Map<String, Object> extendParams) {
        compiledExpression = MVEL.compileExpression(expression, parserContext);
        this.extendParams = extendParams;
    }

    @Override
    public boolean evaluate(Facts facts) {
        DefaultLocalVariableResolverFactory variableResolverFactory =
                new DefaultLocalVariableResolverFactory(this.extendParams);
        if (facts.asMap().size() == 0) {
            //风控处罚时，不带任何参数，直接处罚 facts 为 "[]"
            return true;
        } else {
            Map<String, Object> map = facts.asMap();
            return (boolean) MVEL.executeExpression(compiledExpression, map, variableResolverFactory);
        }
    }
}

